﻿using HelloWorld.Model;
using HelloWorld.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace HelloWorld.Controllers
{
    [Route("api/")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        //[SkipApiResponseFormatting]
        [HttpPost("login")]
        public IActionResult Login([FromBody] UserModel userModel)
        {
            // TODO 省略用户是否存在的检验

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, userModel.Username),
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("12345678901234561234567890123456"));  // 与配置的一致 32个字符
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiry = DateTime.Now.AddDays(1);

            var token = new JwtSecurityToken(
                issuer: "YourIssuer",
                audience: "YourAudience",
                claims: claims,
                expires: expiry,
                signingCredentials: creds
            );

            return Ok(new {token=new JwtSecurityTokenHandler().WriteToken(token)});
        }
    }
}
